package br.com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.controller.LoginControle;
import br.com.connection.ConnectionFactory;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doExecute(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doExecute(request, response);
	}

	protected void doExecute(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		try {
			Connection conn = new ConnectionFactory().getConnection();
			String email = request.getParameter("email");
			String senha = request.getParameter("senha");
			if (email == null || senha == null || !LoginControle.verificaSenha(conn, email, senha)) {
				//request.getSession().setAttribute("msg", "Login ou senha incorretos!!");
				response.sendRedirect("index");
			} else {
				request.getSession().setAttribute("esta_logado", new Boolean(true));
				request.getSession().setAttribute("nome_login", email);
				request.getSession().setAttribute("login_senha", senha);

				response.sendRedirect("/Servico/logado/");
			}
		} catch (SQLException e) {
			e.printStackTrace();
			out.print(e);
		} catch (Exception e) {
			e.printStackTrace();
			out.print(e);
		}

	}
}
